<template>
  <br>
  <div>
    <el-form :model="user" label-width="100px">
      <el-form-item label="ID" v-if="false">
        <el-input v-model="user.id" disabled></el-input>
      </el-form-item>
      <el-form-item label="Username">
        <el-input v-model="username"></el-input>
      </el-form-item>
      <el-form-item label="Password">
        <el-input v-model="password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUser">Update</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script setup>
import {ref} from 'vue';
import axios from 'axios';
import {useRoute} from 'vue-router';
import {urlData} from "@/utils/url.js";
import {useRouter} from "vue-router";

const router = useRouter();

const route = useRoute();
const id = route.params.id;
const user = ref(null);
const username = ref('');
const password = ref('');
//username是否为字母的正则表达式
const usernameReg = /^[a-zA-Z0-9]+$/;
//password是否为字母和数字的正则表达式
const passwordReg = /^[a-zA-Z0-9]+$/;

const validateInput = () => {
  if (username.value === '') {
    ElMessage.error('用户名不能为空');
    return false;
  } else if (!usernameReg.test(username.value)) {
    ElMessage.error('用户名只能包含字母和数字');
    return false;
  } else if (password.value === '') {
    ElMessage.error('密码不能为空');
    return false;
  } else if (!passwordReg.test(password.value)) {
    ElMessage.error('密码只能包含字母和数字');
    return false;
  }
  return true;
};

// 获取用户信息
const fetchUser = () => {
  axios.get(`${urlData('getUserById')}/${id}`)
      .then(response => {
        user.value = response.data.data;
        username.value = user.value.username;
        password.value = user.value.password;
        console.log('User=>', user.value);
      })
      .catch(error => {
        console.error('Error fetching user:', error);
      });
};

// 更新用户信息
//将请求体数据序列化为 URL 编码形式
import qs from 'qs';
import {ElMessage} from "element-plus";

const updateUser = async () => {
  console.log('Update user:', username.value, password.value);
  if (!validateInput()) {
    return;
  }
  try {
    await axios.post(`${urlData('updateUser')}/${id}`, qs.stringify({
          username: username.value,
          password: password.value
        })
    );
    ElMessage.success('修改成功');
    router.push('/detail');
  } catch (error) {
    ElMessage.error('修改失败');
    console.error('Update failed:', error);
  }
};

fetchUser();
</script>

<style scoped>
</style>
